package com.heima.file.service.impl;

import com.heima.file.config.MinIOConfigProperties;
import com.heima.file.service.FileStorageService;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class FileStorageServiceImpl implements FileStorageService {


    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    private static String separator="/";

    /**
     * 构建文件路径
     */
    private String builderFilePath(String prefix, String filename) {
        StringBuilder stringBuilder = new StringBuilder(50);
        if(!StringUtils.isEmpty(prefix)){
            stringBuilder.append(prefix).append(separator);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String now = simpleDateFormat.format(new Date());
        return stringBuilder.append(now).append(separator).append(filename).toString();
    }

    /**
     *  上传图片文件
     * @param prefix  文件前缀
     * @param filename  文件名
     * @param inputStream 文件流
     * @return  文件全路径
     */
    @Override
    public String uploadImgFile(String prefix, String filename, InputStream inputStream){
        String filenamePath = builderFilePath(prefix, filename);
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder().object(filenamePath)
                    .contentType("image/jpg")
                    .bucket(minIOConfigProperties.getBucket())
                    .stream(inputStream, inputStream.available(), -1).build();
            minioClient.putObject(putObjectArgs);
            StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());
            urlPath.append(separator+minIOConfigProperties.getBucket());
            urlPath.append(separator).append(filenamePath);
            return urlPath.toString();
        } catch (Exception e) {
            log.error("minio put file error.",e);
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }
    }



    /**
     *  上传html文件
     * @param prefix  文件前缀
     * @param filename   文件名
     * @param inputStream  文件流
     * @return  文件全路径
     */
    @Override
    public String uploadHtmlFile(String prefix, String filename, InputStream inputStream) {
        String filenamePath = builderFilePath(prefix, filename);
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder().object(filenamePath)
                    .contentType("text/html")
                    .bucket(minIOConfigProperties.getBucket())
                    .stream(inputStream, inputStream.available(), -1).build();
            minioClient.putObject(putObjectArgs);
            StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());
            urlPath.append(separator+minIOConfigProperties.getBucket());
            urlPath.append(separator).append(filenamePath);
            return urlPath.toString();
        } catch (Exception e) {
            log.error("minio put file error.",e);
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }
    }



    /**
     * 删除文件
     * @param pathUrl  文件全路径
     */
    @Override
    public void delete(String pathUrl) {
        String filePath = pathUrl.replace(minIOConfigProperties.getEndpoint() + separator, "");
        int i = filePath.indexOf(separator);
        String bucket = filePath.substring(0, i);
        String file = filePath.substring(i + 1);

        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().object(file).bucket(bucket).build();
        try {
            minioClient.removeObject(removeObjectArgs);
        } catch (Exception e) {
            log.error("minio put file error.",e);
            e.printStackTrace();
            throw new RuntimeException("删除文件失败");
        }

    }

    /**
     * 下载文件
     * @param pathUrl  文件全路径
     * @return
     *
     */
    @Override
    public byte[] downLoadFile(String pathUrl) {
        String filePath = pathUrl.replace(minIOConfigProperties.getEndpoint() + separator, "");
        int i = filePath.indexOf(separator);
        String bucket = filePath.substring(0, i);
        String file = filePath.substring(i + 1);

        //DownloadObjectArgs downloadObjectArgs = DownloadObjectArgs.builder().filename(file).bucket(bucket).build();
        InputStream inputStream=null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder().object(file).bucket(bucket).build());
        } catch (Exception e) {
            log.error("minio put file error.",e);
            e.printStackTrace();
            throw new RuntimeException("删除文件失败");
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while (true) {
            try {
                if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }
}
